package com.iMusic.presentationLayer;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.iMusic.businessLogicLayer.Account;
import com.iMusic.businessLogicLayer.Cart;
import com.iMusic.businessLogicLayer.Order;
import com.iMusic.util.UserMessages;

public class UpdateOrders extends HttpServlet{

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		String redirection = "adminFS.jsp";

		session.removeAttribute("Error");

		Enumeration<String> parameterNames = request.getParameterNames();

		while (parameterNames.hasMoreElements()) {
			String paramName = parameterNames.nextElement();

			int orderId = Integer.parseInt(paramName.substring(paramName.indexOf("_")+1));

			try {
				if (paramName.startsWith("status")) {
					int paramValue = Integer.parseInt(request.getParameter(paramName));
					if (paramValue >= 0)
						Order.updateStatus(orderId, paramValue);
				}
				else if (paramName.startsWith("TN")) {
					String paramValue = request.getParameter(paramName);
					Order.updateTrackingNumber(orderId, paramValue);
				}
			} catch (SQLException e) {
				e.printStackTrace();
				session.setAttribute("Error", UserMessages.INTERNAL_DB_ERROR);
				redirection += "?error="+UserMessages.INTERNAL_DB_ERROR;
			}
			catch (Exception e) {
				e.printStackTrace();
				session.setAttribute("Error", UserMessages.UNKNOWN_ERROR);
				redirection += "?error="+UserMessages.UNKNOWN_ERROR;
			}
		}

		response.sendRedirect(redirection);
	}
}
